package personal.leil.learning.reverse;

import personal.leil.learning.SNode;
import personal.leil.learning.utils.LinkedListUtils;

/**
 * 反转一个单链表
 * <p>
 * 反转一个单链表代码实现
 * </p>
 *
 * @author Leil
 * @version 1.0
 * @since 2024-1-5
 */
public class ReverseSingleLinkedList {

    /**
     * reverse single linked list
     *
     * @param head Head node for single linked list
     * @return Head node for reverse linked list
     */
    public static SNode reverse(SNode head) {
        SNode prev = null;
        SNode current = head;
        while (current != null) {
            SNode next = current.getNext();
            current.setNext(prev);
            // prev、current指针右移
            prev = current;
            current = next;
        }
        return prev;
    }


    /********************* For Test *************************/

    public static SNode buildSingleLinkedList() {
        SNode head = new SNode(1);
        head.setNext(new SNode(2))
            .setNext(new SNode(3))
            .setNext(new SNode(4))
            .setNext(new SNode(5));
        return head;
    }

    public static void main(String[] args) {
        SNode head = buildSingleLinkedList();
        System.out.println("before reverse:");
        LinkedListUtils.printSingleLinkedList(head);

        SNode headAfterReverse = reverse(head);
        System.out.println("after reverse:");
        LinkedListUtils.printSingleLinkedList(headAfterReverse);
    }

}
